package 栈和队列;

import java.util.Stack;

/**
 * @description:
 * @author: ywk
 * @date: 2020-07-01
 */
public class RemoveAdjacentDuplicate {
    public static Stack removeDuplicate(int[] arr) {
        Stack<Integer> stack = new Stack();
        for (int i = 0; i < arr.length; i++) {
            if (!stack.isEmpty() && (stack.peek() != arr[i])) {
                remove(stack);
            }
            stack.push(arr[i]);
            if (i == arr.length - 1) {
                remove(stack);
            }
        }
        return stack;

    }

    public static Stack removeDuplicatew(int[] arr) {
        Stack<Integer> stack = new Stack();
        for (int i = 0; i < arr.length; i++) {
            stack.push(arr[i]);
        }
        Integer pre = null;
        for (int i = 0; i < stack.size();) {
            boolean flag= false;
            while ((i + 1 < stack.size() && stack.get(i) == stack.get(i + 1)) || pre != null &&
                    pre == stack.get(i)) {
                pre = stack.remove(i);
                flag=true;
            }
            if (flag == true) {
                i--;
            }else{
                pre = stack.get(i);
                i++;
            }


        }


        return stack;

}

    public static void remove(Stack<Integer> stack) {
        while (!stack.isEmpty()) {
            Integer cur = stack.pop();
            boolean flag = false;
            while (!stack.isEmpty() && stack.peek() == cur) {
                cur = stack.pop();
                flag = true;
            }
            if (!flag) {
                stack.push(cur);
                break;
            }
        }
    }

    public static void print(Stack stack) {
        while (!stack.isEmpty()) {
            System.out.println(stack.pop());
        }
    }

    public static void main(String[] args) {
        Stack stack = new Stack();
        stack.push(5);
        stack.push(3);
        stack.push(2);
        stack.push(1);
        stack.push(4);
        int[] arr = {1, 9, 6, 8,8, 8,8, 0,8,1,1, 0, 6, 5};
//        int[] arr = {1, 9, 6, 8, 8, 8, 0, 1, 1, 0, 6, 5};
        print(removeDuplicatew(arr));
    }
}
